<?php

namespace app\aiv110\controller;

use app\aiv110\controller\CommonController;
use think\Validate;
use think\Db;
use app\util\Utils;
use app\aiv110\model\Miaosha;
use app\aiv110\model\CtmMiaosha;
use app\aiv110\model\Comment;
use app\aiv110\model\Custom;
use app\aiv110\model\Item;
use app\aiv110\model\Order;
use app\aiv110\model\Yuyue;
use app\aiv110\model\XcxAudit;
use app\aiv110\model\ItemToGoods;
use app\aiv110\model\ItemProcess;
use think\Request;

class MiaoshaController extends CommonController {
    /*
     * code列表
     */

    public function code() {
        /*
         * 0  成功
         * 1  参数错误
         * 2  验证失败
         * 20000  您还没有登录
         * 20001  每个项目的限时抢购每人限购一次
         * 20002  限时抢购还没有开始
         * 20003  该项目已抢光，下次活动早点来哦~去看看其他项目吧~
         * 20004  该项目抢购活动已关闭，去看看其他项目吧~
         * 20004
         */
    }

    /*
     * 秒杀列表
     * author xfwed 
     * date 2019.09.23
     * 
     * @param int perPage 每页数量 非必须，默认20
     * @param int page 当前页数 非必须，默认0
     */

    public function miaoshaList() {
        $rule = [
            'perPage' => 'integer|egt:1',
            'page' => 'integer|egt:0',
        ];
        $msg = [
            'perPage.integer' => '每页数量为数字',
            'perPage.egt' => '每页数量最小为1',
            'page.integer' => '页数为数字',
            'page.egt' => '页数最小为0',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return Utils::ajaxReturn(1, $error, null);
        }

        $perPage = isset($all['perPage']) ? $all['perPage'] : 20;
        $page = isset($all['page']) ? $all['page'] : 0;
        if ($page == 0) {
            $page = 1;
        }

        $type = input('param.type');
        $cityName = Request::instance()->header('cityname');
        $json = '{"str":"'.$cityName.'"}';
        $arr = json_decode($json,true);
        $a = $arr['str'];
        $json = '{"str":"'.$a.'"}';
        $arr = json_decode($json,true);
        $cityName =  $arr['str'];
        
        $offset = ($page - 1) * $perPage;
        $version = input('param.version');
        if ($version) {
            $xcxauditRow = XcxAudit::where('version', $version)->where('is_open', 1)->find();
            if ($xcxauditRow) {
                $where['id'] = ['not in', $xcxauditRow['miaosha_ids']];
            }
        }

        $where['is_del'] = Miaosha::IS_DEL_1;
        $where['start_time'] = ['<', date('Y-m-d H:i:s')];
        $t = date('Y-m-d');
        if($t == '2021-10-17'){
            $m = '1390,1391,1392';
        }elseif ($t == '2021-10-18') {
            $m = '1393,1394,1395';
        }elseif ($t == '2021-10-19') {
            $m = '1396,1397,1398';
        }elseif ($t == '2021-10-20') {
            $m = '1399,1400,1401';
        }elseif ($t == '2021-10-21') {
            $m = '1402,1403,1404';
        }else {
            $m = 0;
        }
        if($m && strpos('三门峡市',$cityName) !== false){
            
        }  else {
            $where['id'] = ['not in',$m];
        }
        $list = Miaosha::with('Item')
                ->where($where)
                //->where('sell_count<number')
                ->field('id,name,item_id,price,number,sell_count')
                ->order('price asc')
                //->limit(0,6)
                ->limit($offset, $perPage)
                ->select();
        foreach ($list as $k => $v) {
            $percent = bcmul(round($v['sell_count'] / $v['number'], 2), 100);
            if ($percent > 100) {
                $percent = 100;
            }
            $list[$k]['percent'] = $percent;
        }
        $picRow = Db::name('pic')
                ->where('type', 9)
                ->where('isshow', 1)
//                ->where('find_in_set(:cityName,city_name)', ['cityName' => $cityName])
//                ->where(function ($query) use ($cityName) {
//                        $query->where('find_in_set(:cityName,city_name)', ['cityName' => $cityName])
//                        ->whereOr('find_in_set(:cityName,city_name)', ['cityName' => '全国']);
//                    })
                ->find();
        if($picRow['city_name'] == '全国' || strpos($picRow['city_name'],$cityName) !== false){
            $pic = $picRow['pic'];
        }  else {
            $pic = '';
        }
        $data['pic'] = $pic;
        $data['list'] = $list;
        $data['note'] = '限时抢购';

        if ($type == 1) {
            return Utils::ajaxReturn(0, '查询成功', $data);
        } else {
            return Utils::ajaxReturn(0, '查询成功', $list);
        }
    }

    /*
     * 秒杀详情
     * author xfwed 
     * date 2019.09.23
     * 
     * @param int id 秒杀id 必须
     * @param int Ctm_id 用户id  非必须
     */

    public function miaoshaInfo() {
        $rule = [
            'id' => 'require|integer',
        ];
        $msg = [
            'id.require' => '秒杀id必须',
            'id.integer' => '秒杀id为数字',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return Utils::ajaxReturn(1, $error, null);
        }
        $id = $all['id'];
        $ctm_id = input('ctm_id');
        $cityName = input('param.cityName');
        $where['id'] = $all['id'];
        $row = Miaosha::with('Item.ItemImg')
                ->field('id,name,item_id,price,number,sell_count')
                ->where($where)
                ->find();
        if ($row['sell_count'] > $row['number']) {
            $row['sell_count'] = $row['number'];
        }
        if (empty($row)) {
            return Utils::ajaxReturn(1, '没有发现该秒杀', NULL);
        }
        $t = date('Y-m-d');
        if($t == '2021-10-17'){
            $m = '1390,1391,1392';
        }elseif ($t == '2021-10-18') {
            $m = '1393,1394,1395';
        }elseif ($t == '2021-10-19') {
            $m = '1396,1397,1398';
        }elseif ($t == '2021-10-20') {
            $m = '1399,1400,1401';
        }elseif ($t == '2021-10-21') {
            $m = '1402,1403,1404';
        }else {
            $m = 0;
        }
        if($cityName){
            $m = explode(",", $m);
            if($cityName != '三门峡市' && in_array($id, $m)){
                return Utils::ajaxReturn(1, '此项目仅限在三门峡地区秒杀', NULL);
            }
        }
        
        $row['percent'] = bcmul(round($row['sell_count'] / $row['number'], 2), 100);
        if ($ctm_id) {//查询用户是否购买了该秒杀
            $ctmMiaoshaRow = CtmMiaosha::where('item_id', '=', $row['item_id'])
                    ->where('ctm_id', '=', $ctm_id)
                    ->find();

            if ($ctmMiaoshaRow) {
                //查询用户的订单号
                $orderdata = Order::alias('o')
                        ->join('ord_pro p', 'o.id = p.ord_id', 'left')
                        ->where('p.type', '=', 5)
                        ->where('p.pro_id', '=', $ctmMiaoshaRow['miaosha_id'])
                        ->where('o.status', '=', 2)
                        ->where('o.ctm_id', $ctm_id)
                        ->field('o.id,o.ord_num,o.store_id')
                        ->find();
                $row['orderdata'] = $orderdata;
                $yuyuedata = Yuyue::where('order_id', '=', $orderdata['id'])
                        //->where('status', 'in', '4,7,8')
//                        ->whereOr(function ($query) {
//                            $query->where('status', 'in', '2,3')
//                            ->where('start_time', '>', date('Y-m-d H:i:s'));
//                        })
                        ->field('id,status,start_time')
                        ->find();
                if (in_array($yuyuedata['status'], [4, 7, 8]) or ( in_array($yuyuedata['status'], [2, 3]) && $yuyuedata['start_time'] > date('Y-m-d H:i:s'))) {
                    $row['is_buy'] = 4; //1未购买且没有待支付的单（立即抢购）2未购买有待支付的单（去付款）3购买了没约呢（去预约）4已购买已预约（已完成）
                } elseif ($yuyuedata['status'] == 6) {
                    $row['is_buy'] = 1;
                } else {
                    $row['yuyuedata'] = $yuyuedata;
                    $row['is_buy'] = 3;
                }
            } else {
                //查询用户是否有待支付的单
                $orderdata = Order::alias('o')
                        ->join('ord_pro p', 'o.id = p.ord_id', 'left')
                        ->where('p.type', '=', 5)
                        ->where('p.pro_id', '=', $id)
                        ->where('o.status', '=', 1)
                        ->where('o.userdel', '=', 1)
                        ->where('o.ctm_id', $ctm_id)
                        ->field('o.id,o.ord_num,o.store_id')
                        ->find();
                $row['orderdata'] = $orderdata;
                if ($orderdata) {
                    $row['is_buy'] = 2;
                } else {
                    $row['is_buy'] = 1;
                }
            }
        } else {
            $row['is_buy'] = 1;
            $row['orderdata'] = null;
        }
        //项目评价
        $row['commentNum'] = Comment::where('item_id', '=', $row['item_id'])->count();
        $commentRow = Comment::where('item_id', '=', $row['item_id'])
                ->where('item_content', 'not null')
                ->order('add_time desc')
                ->field('ctm_id,item_content')
                ->find();
        if ($commentRow) {
            $commentRow['custominfo'] = Custom::where('id', '=', $commentRow['ctm_id'])->field('custom_photo,custom_name,custom_phone')->find();
        }
        $row['newComment'] = $commentRow;
//        //为你推荐
//        $hotItemList = Item::where('is_del', '=', 1)->where('store_id', '=', 0)
//                ->field('id,item_name,item_price,item_img,sell_count')
//                ->order('sell_count desc')
//                ->limit(0, 4)
//                ->select();
//        $row['hotItemList'] = $hotItemList;
        //护理产品
        $itemGoods = ItemToGoods::alias('itg')
                ->join(['goods_info' => 'g'], 'g.id = itg.goods_info_id', 'left')
                ->join(['goods_images' => 'gi'], 'itg.goods_info_id = gi.goods_id', 'left')
                ->where('itg.item_id', $row['item_id'])
                ->where('gi.type', 2)
                ->field('g.id,g.name,g.icon,g.summary,gi.images')
                ->select();
        //服务流程
        $itemProcess = ItemProcess::alias('p')
                ->join(['goods_info' => 'g'], 'g.id = p.good_id', 'left')
                ->join(['goods_images' => 'gi'], 'p.good_id = gi.goods_id and gi.type = 2', 'left')
                ->where('p.item_id', $row['item_id'])
                ->where('p.is_del', 2)
                ->order('p.sort asc')
                ->field('p.name,p.minute,p.facility,p.facility_img,p.good_id,p.content,p.img,g.icon,g.name goodname,g.summary,gi.images')
                ->select();
        //包含的项目
        $imeigroup = Db::name('imeigroup')
                ->where('item_id', $row['item_id'])
                ->where('is_del', 2)
                ->order('sort asc')
                ->field('name,sort,img,content')
                ->select();
        $row['itemGoods'] = $itemGoods;
        $row['itemProcess'] = $itemProcess;
        $row['imeigroup'] = $imeigroup;
        return Utils::ajaxReturn(0, '查询成功', $row);
    }

    /*
     * 秒杀结算
     * 作者 xfwed
     * 日期 2019-09-23
     *
     * @param int ctm_id 登录的客户编号
     * @param int pro_id 体验卡编号
     */

    public function buyMiaosha() {
        $rule = [
            'ctm_id' => 'require|integer',
            'pro_id' => 'require|integer',
        ];
        $msg = [
            'ctm_id.require' => '用户编号必须',
            'ctm_id.integer' => '用户编号为数字',
            'pro_id.require' => '秒杀编号必须',
            'pro_id.integer' => '秒杀编号为数字',
        ];
        $all = input('post.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return Utils::ajaxReturn(1, $error, null);
        }

        $ctm_id = $all['ctm_id'];
        $pro_id = $all['pro_id'];

        if ($ctm_id == 0) {
            return Utils::ajaxReturn(20000, '您还没有登录', null);
        }
        $miaoshaRow = Miaosha::where('id', $pro_id)->field('id,name,start_time,item_id,price,item_price,number,is_del,sell_count')->find();
        $miaoshaRow['name'] = Item::where('id', $miaoshaRow['item_id'])->value('item_name');
        $ctmMiaoshaRow = CtmMiaosha::where('ctm_id', $ctm_id)
                ->where('item_id', '=', $miaoshaRow['item_id'])
                ->find();
        if (!is_null($ctmMiaoshaRow)) {
            return Utils::ajaxReturn(20001, '每个项目的限时抢购每人限购一次~可开通99特权享更多优惠~', null);
        }
        if ($miaoshaRow['start_time'] > date('Y-m-d H:i:s')) {
            return Utils::ajaxReturn(20002, '限时抢购还没有开始', null);
        }
        if ($miaoshaRow['number'] - $miaoshaRow['sell_count'] <= 0) {
            return Utils::ajaxReturn(20003, '该项目已抢光，下次活动早点来哦~可开通99特权享更多优惠~', null);
        }
        if ($miaoshaRow['is_del'] == 2) {
            return Utils::ajaxReturn(20004, '该项目抢购活动已关闭，去看看其他项目吧~', null);
        }

        $model = $this->getModelData();
        $ImgPath = config('appconfig.ImgPath');
        $miaoshaRow['img'] = $ImgPath . $model . '/kkmai/default/miaosha.png';
        //查询用户的零钱
        $ctmData = Custom::where('id', $ctm_id)->field('real_money,red_money,vip_pwd')->find();
        $miaoshaRow['ctmMoney'] = $ctmData['real_money'] + $ctmData['red_money'];
        //$miaoshaRow['ctmMoney'] = $ctmData['real_money'];
        if ($ctmData['vip_pwd']) {
            $is_pwd = 1;
        } else {
            $is_pwd = 2;
        }
        $miaoshaRow['is_pwd'] = $is_pwd;
        return Utils::ajaxReturn(0, '查询成功', $miaoshaRow);
    }

    /*
     * 任务自动发放秒杀
     * 作者 xfwed
     * 日期 2020-06-11
     *
     */

    public function createMiaosha() {
        $miaoshaList = Miaosha::where('is_del', 1)
                ->where('start_time','<',date('Y-m-d H:i:s'))
                ->where('id','not in','1390,1391,1392,1393,1394,1395,1396,1397,1398,1399,1400,1401,1402,1403,1404')
                ->select();
        if (count($miaoshaList) > 0) {
            foreach ($miaoshaList as $k => $v) {
                $data['name'] = $v['name'];
                $data['start_time'] = date('Y-m-d H:i:s');
                $data['item_id'] = $v['item_id'];
                $data['price'] = $v['price'];
                $data['item_price'] = $v['item_price'];
                $data['number'] = 10;
                $data['visit_count'] = 0;
                $data['sell_count'] = 0;
                $data['is_del'] = 1;
                $data['add_time'] = date('Y-m-d H:i:s');
                $data['updated_time'] = date('Y-m-d H:i:s');
                $miaosharow = Miaosha::insertGetId($data);
                if ($miaosharow) {
                    Miaosha::where('id', $v['id'])->update(['is_del' => 2]);
                    if ($v['item_id'] == 117 || $v['item_id'] == 118 || $v['item_id'] == 119) {
                        $miaosha_ids = $miaosharow; //需要下架的秒杀id  多个用逗号隔开
                        $storeList = Db::name('store')
                                ->where('id', 'not in', '10,59,72,81')
                                ->field('id')
                                ->select();
                        foreach ($storeList as $k => $v) {
                            $store_id = $v['id'];
                            $row = Db::name('store_soldoutitem')
                                    ->where('store_id', $store_id)
                                    ->find();
                            if ($row) {//有就是修改
                                if ($row['miaosha_ids']) {
                                    $m = $row['miaosha_ids'] . ',' . $miaosha_ids;
                                } else {
                                    $m = $miaosha_ids;
                                }
                                $save = Db::name('store_soldoutitem')->where('id', $row['id'])
                                        ->update(['miaosha_ids' => $m]);
                            } else {//没有就是新增
                                $insertdata['store_id'] = $store_id;
                                $insertdata['miaosha_ids'] = $miaosha_ids;
                                $insertdata['add_time'] = date('Y-m-d H:i:s');
                                $save = Db::name('store_soldoutitem')->insert($insertdata);
                            }
                        }
                    }
                }
            }
        }
        return Utils::ajaxReturn(0, '执行成功', null);
    }

}
